package com.gezi.admin.config.exception;

import com.gezi.admin.module.config.utils.ResultCodeE;
import com.gezi.admin.module.config.utils.ResultUtil;
import com.gezi.admin.module.config.utils.ResultVo;
import com.gezi.admin.config.exception.type.ApiException;
import com.gezi.admin.config.exception.type.ParamException;
import com.gezi.admin.security.exception.LoginAuthenticationException;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import java.util.List;

/**
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * Exception异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e) {
        log.error("GlobalExceptionHandler-handleException");
        e.printStackTrace();
        if(e instanceof LoginAuthenticationException){
            LoginAuthenticationException authenticationException = (LoginAuthenticationException) e;
            return ResultVo.builder().code(authenticationException.getCode()).message(authenticationException.getChnDesc()).build();
        }
        return ResultVo.builder().code(ResultCodeE.SYS_ERROR.getCode()).message("未知错误，请联系管理员").build();
    }

    /**
     * Exception异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    Object accessDeniedException(AccessDeniedException e) {
        log.error("GlobalExceptionHandler-accessDeniedException");
        e.printStackTrace();
        return ResultVo.builder().code(ResultCodeE.SYS_ERROR.getCode()).message(e.getMessage()).build();
    }

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    Object handleApiException(BindException e) {
        log.error("GlobalExceptionHandler-BindException");
        e.printStackTrace();
        return ResultVo.builder().code(ResultCodeE.DATA_FAIL.getCode()).message(getErrorOne(e.getBindingResult().getAllErrors())).build();
    }

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    Object handleConstraintViolationException(ConstraintViolationException e) {
        log.error("GlobalExceptionHandler-ConstraintViolationException");
        e.printStackTrace();
        return ResultVo.builder().code(ResultCodeE.DATA_FAIL.getCode()).message(e.getConstraintViolations().iterator().next().getMessageTemplate()).build();
    }

    /**
     * 获取第一个错误信息
     * @param allErrors
     * @return
     */
    private static String getErrorOne(List<ObjectError> allErrors) {
        String message = allErrors.get(0).getDefaultMessage();
        log.error(message);
        if(message.startsWith("Failed to convert property")){
            return "数据类型错误";
        }
        return message;
    }

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    Object handleApiException(ApiException e) {
        log.error("GlobalExceptionHandler-handleApiException");
        e.printStackTrace();
        return ResultVo.builder().code(ResultCodeE.DATA_FAIL.getCode()).message(e.getMessage()).build();
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ParamException.class)
    Object handleParamException(ParamException e) {
        log.error("GlobalExceptionHandler-handleParamException");
        e.printStackTrace();
        return ResultVo.builder().code(ResultCodeE.PARAMETER_FAIL.getCode()).message(e.getMessage()).build();
    }

    /**
     * sql异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = MyBatisSystemException.class)
    Object handleMyBatisSystemException(MyBatisSystemException e, HttpServletRequest request) {
        log.error("GlobalExceptionHandler-MyBatisSystemException");
        e.printStackTrace();
        return ResultUtil.error(ResultCodeE.SYS_ERROR.getCode(),"[sql异常]请联系管理员");
    }

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("GlobalExceptionHandler-MethodArgumentNotValidException", e);
        e.printStackTrace();

        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error(message);
        return ResultUtil.error(ResultCodeE.PARAMETER_FAIL.getCode(),message);
    }
}
